import { Button, message as antdMessage, Table, Switch, Popconfirm } from 'antd'
import services from '@/services'
import type { WelcomeMessage } from '@/services/features/welcome-messages'
import EditModal from '../edit'
import './index.module.less'

export default function Content() {
  // ========== 加载列表 ==========
  const [messages, setMessages] = useState<WelcomeMessage[]>([])
  const [loading, setLoading] = useState(false)
  const loadMessages = useCallback(async () => {
    setLoading(true)
    const res = await services.features.welcomeMessages.load()
    if (res.success) setMessages(res.data)
    else void antdMessage.warning('欢迎语列表加载失败：' + res.error)
    setLoading(false)
  }, [])

  useEffect(() => {
    void loadMessages()
  }, [loadMessages])

  // ========== 切换状态 ==========
  const [switching, setSwitching] = useState(false)
  const switchStatus = useCallback(
    async (message: WelcomeMessage) => {
      setSwitching(true)

      const res = await services.features.welcomeMessages.addOrUpdate({
        ...message,
        enable: !message.enable,
      })
      if (res.success) void antdMessage.success('修改状态成功')
      else void antdMessage.warning(`修改状态失败：${res.error}`)

      await loadMessages()
      setSwitching(false)
    },
    [loadMessages],
  )

  // ========== 移除 ==========
  const [removing, setRemoving] = useState(false)
  const remove = useCallback(
    async (id: number) => {
      setRemoving(true)

      const res = await services.features.welcomeMessages.remove(id)
      if (res.success) void antdMessage.success('删除欢迎语成功')
      else void antdMessage.warning(`删除欢迎语失败：${res.error}`)

      await loadMessages()

      setRemoving(false)
    },
    [loadMessages],
  )

  // ========== 创建/编辑 ==========
  const [editing, setEditing] = useState<false | true | WelcomeMessage>(false) // true: 新建  WelcomeMessage: 编辑
  const finishEdit = useCallback(() => {
    setEditing(false)
    void loadMessages()
  }, [loadMessages])

  // ========== 界面 ==========

  const blocking = loading || removing || switching

  const renderStatus = useCallback(
    (rule: WelcomeMessage) => {
      return <Switch
        checked={rule.enable}
        onChange={async () => switchStatus(rule)}
        checkedChildren="开"
        unCheckedChildren="关"
      />
    },
    [switchStatus],
  )

  const renderActions = useCallback(
    (rule: WelcomeMessage) => {
      return <>
        <Button type="link" onClick={() => setEditing(rule)}>
          修改
        </Button>
        <Popconfirm title="确定要删除此规则吗？" onConfirm={async () => remove(rule.id)}>
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>
      </>
    },
    [remove],
  )

  return <div styleName="content">
    <header>
      <Button disabled={blocking} type="primary" onClick={() => setEditing(true)}>
        新建增强欢迎语
      </Button>

      <div styleName="describe">
        欢迎语增强仅是在企微欢迎语基础上增加欢迎语的类型和数量，不可替代企微的欢迎语功能。增强的欢迎语仅在添加好友60秒内且企微欢迎语成功发出时生效，因为企微欢迎语的延迟、丢失等问题，增强欢迎语有一定的失败概率。
      </div>
    </header>

    <Table<WelcomeMessage>
      rowKey="id"
      dataSource={messages}
      scroll={{ y: 300 }}
      pagination={false}
      loading={blocking}
    >
      <Table.Column<WelcomeMessage>
        title="欢迎语名称"
        key="name"
        width={250}
        styleName="name"
        dataIndex="name"
      />
      <Table.Column<WelcomeMessage>
        title="状态"
        key="status"
        width={180}
        styleName="status"
        render={renderStatus}
      />
      <Table.Column<WelcomeMessage>
        title="操作"
        key="actions"
        styleName="actions"
        render={renderActions}
      />
    </Table>

    <EditModal editing={editing} onFinish={finishEdit} />
  </div>
}
